package com.example.hostapp

import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.example.hostapp.databinding.ActivityMainBinding
import kotlin.random.Random


class MainActivity : AppCompatActivity() {
    private val textChangeList = listOf<String>("🍌", "🍎", "🍊", "🍐")
    private lateinit var rootView: View // 根布局视图
    private val TAG = "hostApp"
    private lateinit var binding: ActivityMainBinding
    private lateinit var surfaceView: SurfaceView

    @RequiresApi(Build.VERSION_CODES.R)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        rootView = findViewById(android.R.id.content);

        surfaceView = binding.surView
//        window.decorView.viewTreeObserver.addOnGlobalLayoutListener {
//            val width = window.decorView.width
//            val height = window.decorView.height
//            Log.d(TAG, "surfaceChanged: 尺寸变化了吗！$width*$height")
//            HostManager.sendSurfaceInfo2client(width, height)
//        }

        /**
         * 进行对surface的生命周期进行管理
         */
        surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                // Surface 创建完成，此时可安全操作
                surfaceView.post {
                    HostManager.initSurfaceViewRef(surfaceView)
//                    HostManager.sendSurfaceInfo2client()
                }
            }

            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {
//                // Surface 尺寸变化时的处理
                Log.d(TAG, "surfaceChanged: 尺寸变化了吗！$width*$height")
                HostManager.sendSurfaceInfo2client(width, height)
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {

            }
        })

        /**
         * 初始化改变text的接口
         */
        HostManager.setTextListner(object : HostManager.textListener {
            override fun changeText() {
                val order = Random.nextInt(4)
                Log.d(TAG, "changeText: 随机序号等于==$order")
                binding.tvChange.text = "${binding.tvChange.text} ${textChangeList.get(order)}"
            }
        })
//        surfaceView.post {
//            HostManager.initSurfaceViewRef(surfaceView)
//        }
        binding.btnSur.setOnClickListener {
            HostManager.sendSurfaceInfo2client(surfaceView.width, surfaceView.height)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy: hostApp已经销毁")
    }

}